import axios from '../../../../utils/axios'
Page({
  data: {
    classroom: [],
    studentList: [],// 学生签到
    activeTabIdx: 0,
    homeWork: '',// 作业内容
    images: [],// 选择图片
    columns: [],// 学校课程切换
    curClass: [],// 当前选择的课堂
  },
  async onLoad(options) {
    this.getClassRoomData();
  },
  async getClassRoomData() {
    // 页面缓存优化
    // if (wx.getStorageSync('classroom')) {
    //   let columns = [
    //     { values: [], },
    //     { values: [], }
    //   ];
    //   let classroom = [...wx.getStorageSync('classroom')];
    //   classroom.map((item, idx) => {
    //     // 第一栏
    //     item.school.pickerSchoolIdx = idx;
    //     columns[0].values.push(item.school);
    //     // 第二栏
    //     idx == 0 ? columns[1].values.push(...item.classroomDtos) : ''// 默认第一个的课程
    //   });
    //   let curClass = [
    //     columns[0].values[0],
    //     columns[1].values[0],
    //   ]
    //   this.setData({
    //     columns,
    //     curClass,
    //     classroom,
    //     studentList: columns[1].values[0].studentList
    //   });
    //   return;
    // }
    let schoolRes = await axios({
      url: '/api/coach/search',
      method: 'post',
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    });
    // 遍历学校
    for (let i = 0; i < schoolRes.data.length; i++) {
      let item = schoolRes.data[i];
      // 遍历学生
      for (let j = 0; j < item.classroomDtos.length; j++) {
        let studentListRes = await axios({
          url: '/api/classroom/student',
          data: {
            id: item.classroomDtos[j].id
          },
          header: {
            'Authorization': wx.getStorageSync('token')
          }
        })
        studentListRes.data.map(studentItem => studentItem.signType = 0)
        item.classroomDtos[j].studentList = studentListRes.data;
      }
    };
    console.log('schoolRes', schoolRes);
    let columns = [];
    // picker结构
    columns = [
      {
        values: [],// value-key='name'
      },
      {
        values: [],
      },
    ]
    schoolRes.data.map((item, idx) => {
      // 筛查合法数据
      if (item.classroomDtos.length == 0)
        item.classroomDtos.push({ name: '暂无该校课程', studentList: [] })
      // 第一栏
      item.school.pickerSchoolIdx = idx;
      columns[0].values.push(item.school);
      // 第二栏
      idx == 0 ? columns[1].values.push(...item.classroomDtos) : ''// 默认第一个的课程
    });
    let curClass = [
      columns[0].values[0],
      columns[1].values[0],
    ]
    this.setData({
      columns,
      curClass,
      classroom: schoolRes.data,
      studentList: columns[1].values[0].studentList
    });
    // wx.setStorageSync('classroom', schoolRes.data);
  },
  signIn(e) {
    let idx = e.currentTarget.dataset.idx;
    this.data.studentList[idx].signType = 1;
    wx.showToast({
      title: `${this.data.studentList[idx].name} 签到成功`,
      icon: 'none',
      duration: 1500,
      mask: false,
    });
    this.setData({
      studentList: this.data.studentList
    })
  },
  signOut(e) {
    let idx = e.currentTarget.dataset.idx;
    this.data.studentList[idx].signType = 0;
    wx.showToast({
      title: `${this.data.studentList[idx].name} 已改为未签到`,
      icon: 'none',
      duration: 1500,
      mask: false,
    });
    this.setData({
      studentList: this.data.studentList
    })
  },
  async subSignData() {
    // 转换格式
    let subData = [];
    this.data.studentList.forEach(item => subData.push({
      sid: item.id,
      status: item.signType
    }));
    // 提交
    let res = await axios({
      url: `/api/student/attendance/batch/${this.data.curClass[1].id}`,
      method: 'put',
      data: JSON.stringify(subData),
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    })
    if (res.statusCode == 200)
      wx.showToast({
        title: '提交签到表成功',
        icon: 'success',
        duration: 1500,
        mask: false,
      });
  },
  async subWorkData() {
    if (this.data.homeWork === '') {
      wx.showToast({
        title: '布置作业失败，请输入作业内容',
        icon: 'none',
        duration: 1500,
      });
      return;
    }
    let res = await axios({
      url: '/api/classroom',
      method: 'put',
      data: {
        id: this.data.curClass[1].id,
        homework: this.data.homeWork, // 课后作业
      },
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    });
    wx.showToast({
      title: '布置作业成功',
      icon: 'success',
      duration: 1500,
    });
    this.setData({
      homework: ''
    })
    console.log(res);
  },
  pickerChange(e) {

    let columns = this.data.columns;
    let studentList = [];
    if (this.data.curClass[0].id != e.detail.value[0].id) {
      console.log('school change', columns);
      columns[1].values = this.data.classroom[e.detail.value[0].pickerSchoolIdx].classroomDtos;
      studentList = this.data.classroom[e.detail.value[0].pickerSchoolIdx].classroomDtos[0].studentList;
    }
    else {
      console.log('class change', e.detail.value);
      studentList = e.detail.value[1].studentList;
    }
    this.setData({
      columns,
      studentList,
      curClass: e.detail.value,
    });
  },
  changeVal(e) {
    this.setData({
      homeWork: e.detail.value
    })
  },
  // 通知上课
  async informClass(e) {
    let type = e.currentTarget.dataset.type;
    let res = await axios({
      url: `/api/classroom/${this.data.curClass[1].id}/send/${Number(type)}`,
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    });
    console.log(res);
  },
  // 上传视频
  async subImages() {
    if (this.data.images.length == 0) {
      wx.showToast({
        title: '请先选择要上传的图片',
        icon: 'none',
        duration: 1500,
        mask: false,
      });
      return;
    }
    wx.showLoading({
      title: '上传中...',
      mask: true,
    });
    let upload = async (item) => {
      return new Promise(resolve => {
        wx.uploadFile({
          url: 'https://admin.kenput.cn/api/upload',
          filePath: item,
          name: 'file',
          timeout: 5000,
          success: async res => {
            resolve(JSON.parse(res.data).link);
          }
        })
      });
    };
    for (let i = 0; i < this.data.images.length; i++) {
      let url = await upload(this.data.images[i]);
      let images = this.data.images;
      images[i] = url;
      this.setData({
        images
      });
      if (i == this.data.images.length - 1) {
        console.log('for 后的log');
        let id = this.data.curClass[1].id;
        let images = this.data.images.join();
        let upDateRes = await axios({
          url: `/api/classroom/images?id=${id}&images=${images}`,
          method: 'put',
          header: {
            'Authorization': wx.getStorageSync('token'),
          }
        });
        if (upDateRes.statusCode == 200) {
          wx.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 1500,
          });
          this.setData({
            images: []
          })
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '上传失败',
            icon: 'woring',
            duration: 1500,
            mask: false,
          });
          console.log(upDateRes);
        }
      }
    };
  },
  chooseImage() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        this.setData({
          images: tempFilePaths
        })
        console.log(res);
      },
    });
  },
});

